package com.study4j.oss.qiniu.service.impl;

import java.io.File;
import java.io.InputStream;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.study4j.oss.qiniu.model.QiniuProperties;
import com.study4j.oss.qiniu.service.IQiniuService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
//@EnableConfigurationProperties(QiniuProperties.class)
@ConditionalOnProperty(prefix="oss",name = "type", havingValue = "qiniu")
public class QiniuServiceImpl implements IQiniuService, InitializingBean {

	@Autowired
	private QiniuProperties qiniuProperties;

	@Autowired
	private UploadManager uploadManager;

	@Autowired
	private BucketManager bucketManager;

	@Autowired
	private Auth auth;

	// 定义七牛云上传的相关策略
	private StringMap putPolicy;

	@Override
	public String uploadFile(File file) throws QiniuException {
		Response response = this.uploadManager.put(file, null, getUploadToken());
		int retry = 0;
		while (response.needRetry() && retry < 3) {
			response = this.uploadManager.put(file, null, getUploadToken());
			retry++;
		}
		// 解析结果
		DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
		String return_path = String.format("%s/%s", qiniuProperties.getPrefix(),putRet.key);
		log.info("文件名称={}", return_path);
		return return_path;
	}

	@Override
	public String uploadFile(InputStream inputStream) throws QiniuException {
		Response response = this.uploadManager.put(inputStream, null, getUploadToken(), null, null);
		int retry = 0;
		while (response.needRetry() && retry < 3) {
			response = this.uploadManager.put(inputStream, null, getUploadToken(), null, null);
			retry++;
		}
		// 解析结果
		DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
		String return_path = qiniuProperties.getPrefix() + "/" + putRet.key;
		log.info("文件名称={}", return_path);
		return return_path;
	}

	@Override
	public Response delete(String key) throws QiniuException {
		Response response = bucketManager.delete(qiniuProperties.getBucket(), key);
		int retry = 0;
		while (response.needRetry() && retry++ < 3) {
			response = bucketManager.delete(qiniuProperties.getBucket(), key);
		}
		return response;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		this.putPolicy = new StringMap();
		putPolicy.put("returnBody",
				"{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"width\":$(imageInfo.width), \"height\":${imageInfo.height}}");
		// 自定义文件名字
		// putPolicy.put("saveKey", UUID.randomUUID().timestamp());
	}

	/**
	 * @description 获取上传凭证
	 * @return 上传凭证
	 * @author Jiangbin
	 * @date 2019年7月26日 下午2:45:02
	 */
	private String getUploadToken() {
		return this.auth.uploadToken(qiniuProperties.getBucket(), null, 3600, putPolicy);
	}

}
